package com.xianan.xuhui.netsecurityproject.common;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.xianan.xuhui.netsecurityproject.utils.JsoupUtil;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author xiaoli
 * @description TODO 解决xss攻击，防止sql注入问题
 * @since 2025/3/25 0:42
 */
//@JsonComponent
public class XssJsonDeserializer {
    //不做xss校验的字段，后端的富文本其实是允许潜入一些script的
    public static final List<String> EXCLUDE_LIST = Arrays.asList("content","detail");
    /**
     * 字符串反序列化器
     * 过滤特殊字符，解决 XSS 攻击
     */
    public static class StringDeserializer extends JsonDeserializer<String> {

        @Override
        public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
            if(!EXCLUDE_LIST.contains(jsonParser.getCurrentName())){
                //JsoupUtil过滤掉不安全的字符
                return JsoupUtil.clean(jsonParser.getValueAsString());
            }else{
                return jsonParser.getValueAsString();
            }

        }
    }
}
